package com.irs.irsforum.service.impl;

import com.irs.irsforum.entity.Favorite;
import com.irs.irsforum.mapper.FavoriteMapper;
import com.irs.irsforum.mapper.PostMapper;
import com.irs.irsforum.service.IFavoriteService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.irs.irsforum.web.FavoriteController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yihuili
 * @since 2020-01-18
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {
    private static final Logger logger =
            LoggerFactory.getLogger(FavoriteServiceImpl.class);

    @Autowired
    FavoriteMapper favoriteMapper;

    @Autowired
    PostMapper postMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer setFavorite(Long postId, Long userId) throws SQLException {
        Integer isExist = postMapper.hasPost(postId);
        Integer result;
        if (isExist == null || isExist == 0) {
            logger.error("帖子不存在");
            return 0;
        }
        Integer favoriteType = favoriteMapper.isFavorite(postId, userId);
        if (favoriteType != null && favoriteType == 1) {
            return favoriteType;
        } else if (favoriteType != null && favoriteType == 0) {
            result = favoriteMapper.updateFavorite(new Favorite(postId, userId, 1));
        } else {
            try {
                result = favoriteMapper.setFavorite(postId, userId);
            } catch (Exception e) {
                throw new SQLException("插入异常");
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cancelFavorite(Long postId, Long userId) {
        Integer result = favoriteMapper.updateFavorite(new Favorite(postId, userId, 0));
        return result;
    }
}
